<template>
	<view class="toast" v-if="show" @transitionend="transitionend" ref='toast' :animation="animationData">
		<text class='toast-text'>{{message}}</text>
	</view>
</template>

<script>
	import { ref,nextTick,getCurrentInstance,onMounted } from "vue";
	export default {
		setup(){
			const visible = ref(false);
			const show = ref(false);
			const message = ref("");
			const animationData = ref({});
			const animation = uni.createAnimation({
				duration: 600,
				timingFunction: 'ease',
				delay: 0
			});
			const { ctx } = getCurrentInstance();
			onMounted(() => {
				getApp().globalData.setToast((mes) => {
					animationData.value = {};
					n = 0;
					message.value = mes;
					if(show.value){
						show.value = false;
					}
					nextTick(() => {
						show.value = true;
						const query = uni.createSelectorQuery().in(ctx);
						let view = query.select(".toast");
						//reflow
						view.boundingClientRect(data => {
							animation.opacity(1).translate3d('-50%',0,0).step();
							animation.opacity(0).step({
								delay: 2000
							});
							animationData.value = animation.export();
						}).exec();
					});
				});
			});
			let n = 0;
			function transitionend(e){
				// console.log(e,n);
				if(++n === 3){
					n = 0;
					show.value = false;
					animationData.value = {};
				}
			}
			return {
				visible,
				message,
				show,
				animationData,
				transitionend,
			};
		}
	}
</script>

<style>
.toast{
  position: fixed;opacity: 0;
	left: 50%;bottom: 100px;
	text-align: center;
	z-index: 1060;
  transform : translate3d(-50%,200%,0);
  -webkit-transform : translate3d(-50%,200%,0);
	/* transition-property: transform,opacity;
	-webkit-transition-property: transform,opacity; */
	transition-duration: 600;
	-webkit-transition-duration: 600;
	transition-timing-function: linear;
	-webkit-transition-timing-function: linear;
}
.toast-text{
	max-width: 600rpx;
  display: inline-block;
	padding: 8px 12px;
	border-radius: 5px;
	background-color: rgba(0,0,0,0.8);
	font-size: 14px;
  color: #fff;
}
</style>
